package com.timothy.remote.client;

import javax.annotation.PostConstruct;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.timothy.remote.core.PermissionContext;
import com.timothy.remote.core.RemoteServiceInterface;
import com.timothy.remote.core.UserEntity;

@Service
public class ClientShiroRealm extends AuthorizingRealm {

	@Autowired
	private ClientShiroProperties shiroProperties;
	@Autowired
	private RemoteServiceInterface remoteService;

	@PostConstruct
	public void realmInit() {
		this.setAuthorizationCacheName(shiroProperties.getRedisAuthCacheName());
	}

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		UserEntity user = (UserEntity) SecurityUtils.getSubject().getPrincipal();
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		PermissionContext context = remoteService.getPermissions(user.getPhone());
		authorizationInfo.setStringPermissions(context.getPermissions());
		return authorizationInfo;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		// 永远不会被调用
		throw new UnsupportedOperationException("永远不会被调用");
	}

}
